#! /usr/bin/python
# -*- coding: utf-8 -*-

"""GUI of the ftp client
"""
import wx
import sys, os
from Qftp import Qftp
from multiprocessing import Process
from threading import Thread
from fetchDouban import fetchComment

ID_CONNECT = 5
ID_DISCONNECT = 6

class smartui(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, -1, title, size = (800,480))
        self.ftp1 = Qftp('202.117.54.250', '4021', 'list', 'list', 'gb18030')
        self.savedir = os.getcwd()
        self.toolbar1 = wx.ToolBar(self, -1, style = wx.TB_HORIZONTAL|wx.NO_BORDER)
        self.toolbar1.AddLabelTool(ID_CONNECT,'go',wx.Bitmap('./icons/1.png'),\
                            shortHelp='connect', longHelp = 'connect to the server')
        self.toolbar1.AddLabelTool(ID_DISCONNECT,'disconnect',wx.Bitmap('./icons/2.png'),\
                            shortHelp='disconnect from server', longHelp = 'dis connect from server ...')
        self.toolbar1.SetBackgroundColour(wx.WHITE)
        self.toolbar1.SetToolBitmapSize((64, 64))
        self.toolbar1.Realize()
        self.Bind(wx.EVT_TOOL, self.OnConnect, id = ID_CONNECT)
        self.Bind(wx.EVT_TOOL, self.OnDisConnect, id = ID_DISCONNECT)
        self.toolbar1.EnableTool(ID_CONNECT, True)
        self.toolbar1.EnableTool(ID_DISCONNECT, False)
#        panel = wx.Panel(self, -1, style = wx.NO_BORDER)
#        tbtn = platebtn.PlateButton(panel, wx.ID_ANY, 'hihi', wx.Bitmap('./icons/1.png'), style = platebtn.PB_STYLE_GRADIENT | platebtn.PB_STYLE_NOBG)
#        tbtn2 = platebtn.PlateButton(panel, wx.ID_ANY, 'hihi', wx.Bitmap('./icons/3.png'), style = platebtn.PB_STYLE_GRADIENT | platebtn.PB_STYLE_NOBG)
#        hbox1 = wx.BoxSizer()
#        hbox1.Add(tbtn, 0)
#        hbox1.Add(tbtn2, 0)
        self.toolbar2 = wx.ToolBar(self, -1, style = wx.VERTICAL|wx.NO_BORDER)
        self.toolbar2.AddLabelTool(-1,'go',wx.Bitmap('./icons/4.png'),\
                            shortHelp='connect', longHelp = 'connect to the server')
        self.toolbar2.AddLabelTool(-1,'reserve',wx.Bitmap('./icons/2.png'),\
                            shortHelp='reserve', longHelp = 'reserve ...')
        
#        self.toolbar2.AddControl(tbtn)
        self.toolbar2.SetBackgroundColour(wx.WHITE)
        self.toolbar2.SetToolBitmapSize((64, 64))
        self.toolbar2.Realize()
        #panel = wx.Panel(self, -1)
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.splitter = wx.SplitterWindow(self, -1, style = wx.SP_BORDER)
        self.splitter.SetMinimumPaneSize(50)
        self.list1 = wx.ListCtrl(self.splitter, -1, style = wx.LC_REPORT)
        panel1 = wx.Panel(self.splitter, -1)
        self.text1 = wx.TextCtrl(panel1, -1, "",style=wx.TE_MULTILINE)
        self.text1.SetEditable(False)
        self.text1.write('smart ftp 3.0 alpha... \nwelcome\n')
#        self.text1.SetBackgroundColour("#515151")
        self.text1.SetForegroundColour(wx.BLUE)
        self.text2 = wx.TextCtrl(panel1, -1, "",style=wx.TE_MULTILINE|wx.TE_RICH2)
        self.text2.SetEditable(False)
        self.ftp1.setlog(self.text1)
        vbox_b = wx.BoxSizer(wx.VERTICAL)
        vbox_b.Add(self.text1, 1, wx.EXPAND|wx.BOTTOM|wx.TOP,0)
        vbox_b.Add(self.text2, 2, wx.EXPAND|wx.BOTTOM|wx.TOP,8)
        panel1.SetSizer(vbox_b)
#        self.list2 = wx.ListCtrl(self.splitter, -1, style = wx.LC_REPORT)
        
#        self.list2.InsertColumn(0,'file name')
#        self.list2.InsertColumn(1,'file size')
#        self.list2.SetColumnWidth(0, 200)
#        self.list2.SetColumnWidth(1, 100)
        self.list1.InsertColumn(0,'file name')
        self.list1.InsertColumn(1,'file size')
        self.list1.SetColumnWidth(0, 200)
        self.list1.SetColumnWidth(1, 100)
        images = ['./icons/home1.png','./icons/folder.png', './icons/file.png']
        self.list1.il = wx.ImageList(16,16)
        for i in images:
            self.list1.il.Add(wx.Bitmap(i))
        self.list1.SetImageList(self.list1.il, wx.IMAGE_LIST_SMALL)
        self.splitter.SplitVertically(self.list1, panel1)
        
        self.Bind(wx.EVT_LIST_ITEM_FOCUSED, self.OnListFocus, id = wx.ID_ANY)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnListRClick, id = wx.ID_ANY)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnListActivated, id = wx.ID_ANY)
        vbox.Add(self.toolbar1, 0, wx.EXPAND|wx.LEFT|wx.TOP, -1)
        vbox.Add(self.splitter, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, 8)
        hbox = wx.BoxSizer()
        hbox.Add(self.toolbar2, 0, wx.LEFT|wx.TOP, -1)
        hbox.Add(vbox, 1, wx.EXPAND|wx.LEFT|wx.RIGHT,-1)
        self.SetSizer(hbox)
        self.SetAutoLayout(True)
        self.CreateStatusBar()
        self.Center()
        self.Show(True)
        
    def ConnectAndList(self, list, startdir):
#        self.ftp1.connect()
        listDic = self.ftp1.list_dir(startdir)
        if listDic is None: return
        list.DeleteAllItems()
        list.InsertStringItem(0,'..')
        list.SetItemImage(0,0)
        for dic in listDic:
            if dic['is_dir'] is True:
                index = list.InsertStringItem(sys.maxint, dic['name'])
                list.SetStringItem(index, 1, dic['size'])
                list.SetItemImage(index, 1)
                if index%2 == 0:
                    list.SetItemBackgroundColour(index,'#e6f1f5')
        for dic in listDic:
            if dic['is_dir'] is not True:
                index = list.InsertStringItem(sys.maxint, dic['name'])
                list.SetStringItem(index, 1, dic['size'])
                list.SetItemImage(index, 2)
                if index%2 == 0:
                    list.SetItemBackgroundColour(index,'#e6f1f5')
                    
    def download(self, srcdir):
        self.ftp2 = Qftp('202.117.54.250', '4021', 'movie', 'movie', 'gb18030')
        self.ftp2.setlog(self.text1)
        self.ftp2.download(srcdir, self.savedir)
        
    def OnConnect(self, event):
        p_conn = Thread(target = self.ConnectAndList, args = (self.list1,'/'))
        p_conn.start()
        self.toolbar1.EnableTool(ID_CONNECT, False)
        self.toolbar1.EnableTool(ID_DISCONNECT, True)
        
    def OnDisConnect(self, event):
        self.ftp1.quit()
        self.toolbar1.EnableTool(ID_CONNECT, True)
        self.toolbar1.EnableTool(ID_DISCONNECT, False)
             
    def OnListFocus(self, event):
        self.SetStatusText('on list focus')
        item = event.GetItem()
        item.SetBackgroundColour(wx.RED)
        item.SetText('action..')
        
    def OnListRClick(self, event):
        index = self.list1.GetFirstSelected()
#        print self.list2.GetItemText(index)
#        item = self.list2.GetItem(index, 1)
#        print item.GetText()
        self.popupID1 = wx.NewId()
        self.popupID2 = wx.NewId()
        self.popupID3 = wx.NewId()
        self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)
        self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)
        self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)
        menu = wx.Menu()
        menu.Append(self.popupID1, 'download them all')
        menu.Append(self.popupID2, 'retrieve commentary')
        menu.Append(self.popupID3, 'enter')
        self.PopupMenu(menu)
        menu.Destroy()
        
    def OnPopupOne(self, event):
        index = self.list1.GetFirstSelected()
        cwd = self.ftp1.pwd().decode('gb18030')
        if cwd == '/':
            dir = cwd+self.list1.GetItemText(index)
        else:
            dir = '/'.join([cwd, self.list1.GetItemText(index)])
        print 'download dir:'
        print dir
        p = Thread(target = self.download,args = (dir,))
        p.start()
        #self.list2.SetItemBackgroundColour(, wx.RED)
        print 'OnPopupOne'
    
    def getComment(self, Text):
        movieInfo, comment = fetchComment(Text)
        self.text2.Clear()
        if movieInfo is None:
            return
        averageRating = movieInfo['averageRating']
        raters = movieInfo['raters']
        title = movieInfo['title']
        content = movieInfo['content']
        f = wx.Font(9, wx.ROMAN,wx.FONTSTYLE_NORMAL, wx.BOLD)
        self.text2.SetStyle(44, 47, wx.TextAttr("GREEN", "BLACK",f))
        self.text2.WriteText('from douban.com\n')
        self.text2.SetStyle(44, 47, wx.TextAttr("BLACK", "WHITE",f))
        self.text2.WriteText('\n')
        f = wx.Font(10, wx.ROMAN, wx.ITALIC, wx.BOLD)
        self.text2.SetStyle(60, 60, wx.TextAttr("RED", "WHITE",f))
        self.text2.WriteText('average %s star, %s persons rated\n' % (averageRating, raters))
        f = wx.Font(14, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.BOLD)
        self.text2.SetStyle(100, 100, wx.TextAttr("BLUE", "WHITE",f))
        self.text2.WriteText(title+'\n')
        f2 = wx.Font(11, wx.FONTFAMILY_MODERN,wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
        self.text2.SetStyle(100, 100, wx.TextAttr("BLACK", "WHITE",f2))
        self.text2.WriteText(content)
        self.text2.WriteText('\n\n')
        
        for entry in comment:
            f = wx.Font(12, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.BOLD)
            self.text2.SetStyle(1800, 1800, wx.TextAttr("DARK GREEN", "WHITE",f))
            self.text2.WriteText(entry[0]+'\n')
            f = wx.Font(11, wx.FONTFAMILY_MODERN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
            self.text2.SetStyle(1800, 1800, wx.TextAttr("BLACK", "WHITE",f))
            self.text2.WriteText(entry[1]+'\n\n')
        self.text2.SetInsertionPoint(0)
        
    def OnPopupTwo(self, event):
        index = self.list1.GetFirstSelected()
        origText = self.list1.GetItemText(index)
        p = Thread(target = self.getComment, args = (origText,))
        p.start()
#        print content
        
    def OnPopupThree(self, event):
        print 'OnPopupThree'
        

    def OnListActivated(self, event):
        index = self.list1.GetFirstSelected()
        base = self.list1.GetItemText(index)
        cur = self.ftp1.pwd()
        if cur == '/':
            dir = cur+base
        elif base == '..':
            dir, base = os.path.split(self.ftp1.pwd().decode('gb18030'))
        else:
            dir = '/'.join([self.ftp1.pwd().decode('gb18030'), self.list1.GetItemText(index)])
        print 'dir is:',
        print dir
        p = Thread(target = self.ConnectAndList, args = (self.list1, dir))
        p.start()

if __name__ == '__main__':
    app = wx.App()
    smartui(None, -1, 'File Hunter')
    app.MainLoop()
